package com.jiangxiaofei.citycloud.activity.fleamarket;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.blankj.utilcode.util.EmptyUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jiangxiaofei.citycloud.R;
import com.jiangxiaofei.citycloud.activity.user.LoginAcitivity;
import com.jiangxiaofei.citycloud.adapter.GoodListAdapter;
import com.jiangxiaofei.citycloud.adapter.FleaRecyTypeAdapter;
import com.jiangxiaofei.citycloud.base.BaseActivity;
import com.jiangxiaofei.citycloud.bean.GoodListBean;
import com.jiangxiaofei.citycloud.bean.FleaMenuBean;
import com.jiangxiaofei.citycloud.constants.Constants;
import com.jiangxiaofei.citycloud.constants.StringConstants;
import com.jiangxiaofei.citycloud.mvp.FleaConstant;
import com.jiangxiaofei.citycloud.mvp.FleaPersenter;
import com.jiangxiaofei.citycloud.param.FleaGoodListParam;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.footer.BallPulseFooter;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

/**
 * @author: JiangXFei
 * @date: 2017/11/14 0014
 * @content: 商品筛选列表页面
 */

public class FleaMarketGoodsListActivity extends BaseActivity
        implements FleaConstant.GetGoodListView, FleaConstant.GetFleaMenuView {
    @InjectView(R.id.img_back)
    ImageView imgBack;
    @InjectView(R.id.tv_search_type)
    TextView tvSearchType;
    @InjectView(R.id.et_search)
    TextView etSearch;
    @InjectView(R.id.linear_search)
    LinearLayout linearSearch;
    @InjectView(R.id.img_publish)
    TextView imgPublish;
    @InjectView(R.id.tv_goods_date)
    TextView tvGoodsDate;
    @InjectView(R.id.tv_goods_instance)
    TextView tvGoodsInstance;
    @InjectView(R.id.tv_goods_type)
    TextView tvGoodsType;
    @InjectView(R.id.tv_goods_price)
    TextView tvGoodsPrice;
    @InjectView(R.id.recy_goods)
    RecyclerView recyGoods;
    @InjectView(R.id.ref_layout)
    SmartRefreshLayout refLayout;

    private PopupWindow mPopupWindowPublish;
    private View popupView;
    private FleaConstant.GetGoodListPersenter getGoodListPersenter;
    private FleaGoodListParam param;
    private int id;
    private int page;
    private String lat;
    private String lng;
    private List<GoodListBean> goodListBeans = new ArrayList<>();
    private GoodListAdapter goodListAdapter;
    private List<FleaMenuBean> fleaMenuType = new ArrayList<>();
    private FleaConstant.GetFleanMenuPersenter getFleanMenuPersenter;
    private FleaRecyTypeAdapter typeAdapter;
    private PopupWindow mTypePopupWindow;
    private View view;
    private RecyclerView recyType;
    private BDLocation bdLocation;

    @Override
    protected void initView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_flea_good_list_layout);
        mContext = this;
        mActivity = this;
        ButterKnife.inject(this);
        initPopupPublish();
        initRecy();
        initRefLayout();
        //初始化请求商品列表
        getGoodListPersenter = new FleaPersenter(mContext, (FleaConstant.GetGoodListView) mActivity);
        Intent intent = getIntent();
        id = intent.getIntExtra(StringConstants.FLEATYPEID, 0);
        page = 1;
        if (EmptyUtils.isNotEmpty(Constants.bdLocation)) {
            bdLocation = Constants.bdLocation;
        } else {
            Constants.bdclient.start();
            bdLocation = Constants.bdLocation;
        }
        lat = String.valueOf(bdLocation.getLatitude());
        lng = String.valueOf(bdLocation.getLongitude());
        initParam();
        initPopup();
        getFleanMenuPersenter = new FleaPersenter(mContext, (FleaConstant.GetFleaMenuView) mActivity);
        getFleanMenuPersenter.getFleaThreeMenu();
        getGoodListPersenter.getGoodList();
    }

    //初始化请求参数
    private void initParam() {
        param = new FleaGoodListParam();
        param.setId(id);
        param.setLat(lat);
        param.setLng(lng);
        param.setPage(page);
        param.setDis(null);
        param.setIssue(null);
        param.setPrice(null);
    }

    /**
     * 初始化刷新框架
     */
    private void initRefLayout() {
        refLayout.setRefreshHeader(new MaterialHeader(this).setShowBezierWave(true));
//        .setPrimaryColors(0xff66caff);
        refLayout.setRefreshFooter(new BallPulseFooter(this).setSpinnerStyle(SpinnerStyle.Scale));

        refLayout.setOnLoadmoreListener(refreshlayout -> {
            refreshlayout.finishLoadmore(2000);
            page++;
            param.setPage(page);
            getGoodListPersenter.getGoodList();
        });
        refLayout.setOnRefreshListener(refreshlayout -> {
            refreshlayout.finishRefresh(2000);
            page = 1;
            param.setPage(page);
            goodListBeans.clear();
            getGoodListPersenter.getGoodList();
        });
    }

    /**
     * 初始化列表展示适配器
     */
    private void initRecy() {
        goodListAdapter = new GoodListAdapter(R.layout.item_flea_have_goods_layout, goodListBeans);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
        recyGoods.setLayoutManager(linearLayoutManager);
        goodListAdapter.setOnItemClickListener((adapter, view, position) -> {
            Intent intent = new Intent(mContext, FleaMarketGoodsDetailActivity.class);
            intent.putExtra(StringConstants.FLEAGOODID, Integer.valueOf(goodListBeans.get(position).getId()));
            mActivity.startActivity(intent);
        });
        recyGoods.setAdapter(goodListAdapter);
    }

    @Override
    protected void setListener() {

    }

    @Override
    protected void processLogic(Bundle savedInstanceState) {

    }

    /**
     * 设置按钮点击事件
     */
    @OnClick({R.id.img_back, R.id.linear_search, R.id.img_publish, R.id.tv_goods_date,
            R.id.tv_goods_instance, R.id.tv_goods_type, R.id.tv_goods_price})
    public void bOnClick(View v) {
        switch (v.getId()) {
            default:
                break;
            case R.id.img_back:
                //返回
                mActivity.finish();
                break;
            case R.id.linear_search:
                //搜索
                mActivity.startActivity(new Intent(mContext, FleaMarketSearchActivity.class));
                break;
            case R.id.img_publish:
                //发布
                if (EmptyUtils.isEmpty(Constants.userInfo)) {
                    startActivity(new Intent(this, LoginAcitivity.class));
                }else{
                    showPopup();
                }
                break;
            case R.id.tv_goods_date:
                //发布时间
                setTextColor(tvGoodsDate);
                goodListBeans.clear();
                initParam();
                param.setIssue("0");
                getGoodListPersenter.getGoodList();
                break;
            case R.id.tv_goods_instance:
                //距离
                setTextColor(tvGoodsInstance);
                goodListBeans.clear();
                initParam();
                param.setDis("0");
                getGoodListPersenter.getGoodList();
                break;
            case R.id.tv_goods_type:
                // 类别
                setTextColor(tvGoodsType);
                goodListBeans.clear();
                mTypePopupWindow.showAsDropDown(tvGoodsType);
                initParam();
                param.setId(id);
                break;
            case R.id.tv_goods_price:
                //价格
                setTextColor(tvGoodsPrice);
                initParam();
                goodListBeans.clear();
                param.setPrice("0");
                getGoodListPersenter.getGoodList();
                break;

        }
    }

    private void setTextColor(TextView textView) {
        tvGoodsDate.setTextColor(Color.parseColor("#7b7b7b"));
        tvGoodsInstance.setTextColor(Color.parseColor("#7b7b7b"));
        tvGoodsType.setTextColor(Color.parseColor("#7b7b7b"));
        tvGoodsPrice.setTextColor(Color.parseColor("#7b7b7b"));
        textView.setTextColor(Color.parseColor("#4abefb"));
    }

    /**
     * 初始化分类popupWindow
     */
    private void initPopup() {
        mTypePopupWindow = new PopupWindow(mContext);
        view = LayoutInflater.from(mContext).inflate(R.layout.popup_flea_type_item_layout, null);
        mTypePopupWindow.setContentView(view);
        mTypePopupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        mTypePopupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        mTypePopupWindow.setFocusable(true);
        mTypePopupWindow.setBackgroundDrawable(new ColorDrawable(0x00000000));
        recyType = view.findViewById(R.id.recy_type_item);
        typeAdapter = new FleaRecyTypeAdapter(R.layout.item_flea_popup_text_layout, fleaMenuType);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
        recyType.setLayoutManager(linearLayoutManager);
        typeAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                for (int i = 0; i < fleaMenuType.size(); i++) {
                    fleaMenuType.get(i).setChecked(false);
                }
                fleaMenuType.get(position).setChecked(true);
                id = Integer.valueOf(fleaMenuType.get(position).getId());
                initParam();
                param.setId(id);
                getGoodListPersenter.getGoodList();
                typeAdapter.notifyDataSetChanged();
                mTypePopupWindow.dismiss();
                goodListAdapter.notifyDataSetChanged();
            }
        });
        recyType.setAdapter(typeAdapter);
    }

    /**
     * 初始化发布popupWindow
     */
    private void initPopupPublish() {
        mPopupWindowPublish = new PopupWindow(mContext);
        popupView = LayoutInflater.from(mContext).inflate(R.layout.popup_ios_buttom, null);
        showAnimation(popupView);
        mPopupWindowPublish.setContentView(popupView);
        mPopupWindowPublish.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        mPopupWindowPublish.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        mPopupWindowPublish.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        mPopupWindowPublish.setFocusable(true);
        mPopupWindowPublish.setOutsideTouchable(false);
        TextView tvGong = popupView.findViewById(R.id.tv_publish_gong);
        TextView tcXu = popupView.findViewById(R.id.tv_publish_xu);
        TextView tvCannel = popupView.findViewById(R.id.tv_cannel);
        tvGong.setOnClickListener(v -> {
            mPopupWindowPublish.dismiss();
            startActivity(new Intent(mContext, FleaMarketHavePublishActivity.class));
        });
        tvCannel.setOnClickListener(v -> mPopupWindowPublish.dismiss());
        tcXu.setOnClickListener(v -> {
            mPopupWindowPublish.dismiss();
            startActivity(new Intent(mContext, FleaMarketNeedPublishActivity.class));
        });
    }

    public void showPopup() {
        showAnimation(popupView);
        mPopupWindowPublish.showAtLocation(getCurrentFocus(), Gravity.BOTTOM, 0, 0); // 设置背景颜色变暗
        WindowManager.LayoutParams lp = mActivity.getWindow().getAttributes();
        lp.alpha = 0.7f;
        mActivity.getWindow().setAttributes(lp);
        mPopupWindowPublish.setOnDismissListener(() -> {
            WindowManager.LayoutParams lp1 = mActivity.getWindow().getAttributes();
            lp1.alpha = 1f;
            mActivity.getWindow().setAttributes(lp1);
        });
    }

    private void showAnimation(View popView) {
        AnimationSet animationSet = new AnimationSet(false);
        AlphaAnimation alphaAnimation = new AlphaAnimation(0f, 1.0f);
        alphaAnimation.setDuration(300);
        TranslateAnimation translateAnimation = new TranslateAnimation(
                Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f,
                Animation.RELATIVE_TO_SELF, 1f, Animation.RELATIVE_TO_SELF, 0f
        );
        translateAnimation.setDuration(300);
        animationSet.addAnimation(alphaAnimation);
        animationSet.addAnimation(translateAnimation);
        popView.startAnimation(animationSet);
    }

    @Override
    public void setData(Object o) {

    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void message(String str) {

    }

    @Override
    public FleaGoodListParam getGoodListParam() {
        return param;
    }

    @Override
    public void goodListSuccess(List<GoodListBean> goodListBeans) {
        if (goodListBeans.size() > 0) {
            this.goodListBeans.addAll(goodListBeans);
            goodListAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public int getFleaMenu() {
        return id;
    }

    @Override
    public void getFleaMainMenuOnSuccess(List<FleaMenuBean> fleaMenuBeans) {

    }

    @Override
    public void getFleaSencendMenuOnSuccess(List<FleaMenuBean> fleaMenuBeans) {

    }

    @Override
    public void getFleaThreeMenuOnSuccess(List<FleaMenuBean> fleaMenuBeans) {
        fleaMenuType.clear();
        if (fleaMenuBeans.size() > 0) {
            fleaMenuType.addAll(fleaMenuBeans);
        }
        typeAdapter.notifyDataSetChanged();
    }
}
